<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入设备名称"
        v-model="queryForm.name"
      >
      </el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入设备板地址"
        v-model="queryForm.boardAddr"
      >
      </el-input>
      <!-- <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入SN编号"
        v-model="queryForm.snCode"
      >
      </el-input> -->
      <!-- <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="通信号码"
        v-model="queryForm.termiPhoneNum"
      >
      </el-input> -->
      <!-- <el-select
        clearable
        style="width: 200px"
        class="filter-item"
        v-model="queryForm.connectStatus"
        placeholder="设备在线状态"
      >
        <el-option
          v-for="(val, key) in connectStatus"
          :key="key"
          :label="val"
          :value="key"
        >
        </el-option>
      </el-select> -->
      <el-select
        clearable
        style="width: 200px"
        class="filter-item"
        v-model="queryForm.deviceType"
        placeholder="设备类型"
      >
        <el-option
          v-for="(val, key) in Dicts.DEVICE_TYPE"
          :key="key"
          :label="val"
          :value="key"
        >
        </el-option>
      </el-select>
      <el-button
        class="filter-item"
        @click="doSearchQuery"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-button
        v-permission="'device:add'"
        class="filter-item"
        style="margin-left: 10px;"
        @click="openCreateDialog"
        type="success"
        icon="el-icon-plus"
        >新增</el-button
      >

      <el-popover
        width="500"
        height="300"
        title="选择列"
        placement="right-end"
        style="float:right;margin-right:30px;"
        trigger="click"
      >
        <el-checkbox-group v-model="colOptions">
          <el-checkbox
            v-for="item in colSelect"
            :label="item"
            :key="item"
          ></el-checkbox>
        </el-checkbox-group>
        <el-button slot="reference" style="width:100px;">选择列</el-button>
      </el-popover>

      <div style="display: flex;line-height: 36px;justify-content: right;">
        <span style="color: white;font-weight: bold;"
          >数据刷新周期:&nbsp;&nbsp;</span
        ><el-select
          v-model="refreshTime"
          class="filter-item"
          @change="timeChange"
          placeholder="请选择数据刷新周期"
          style="width:100px;float:right;margin-right:15px;"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
    </div>

    <el-table
      v-loading="loading"
      @sort-change="handleSortChange"
      :data="records"
      ref="tableDataRef"
      style="width: 99.9%;"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="tableExpand">
            <el-form-item label="设备编号：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;&#12288;{{ props.row.deviceCode }}</span
              >
            </el-form-item>
            <el-form-item label="SN编号：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;&#12288;{{ props.row.snCode }}</span
              >
            </el-form-item>
            <el-form-item label="设备名称：" class="tableExpanditem">
              <span class="tableExpandspan">&#12288;{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item label="所属企业：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;{{ props.row.bussinessName }}</span
              >
            </el-form-item>
            <el-form-item label="所属项目：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;&#12288;{{ props.row.projectName }}</span
              >
            </el-form-item>
            <el-form-item label="设备类型：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;&#12288;{{
                  Dicts.DEVICE_TYPE[props.row.deviceType]
                }}</span
              >
            </el-form-item>
            <el-form-item label="硬件版本：" class="tableExpanditem">
              <span class="tableExpandspan">
                &#12288;{{
                  Dicts.DEVICE_HARDWARE_VER[props.row.localHwVer]
                }}</span
              >
            </el-form-item>
            <el-form-item label="软件版本：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;{{ props.row.localSwVer }}</span
              >
            </el-form-item>
            <el-form-item label="连接方式：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;&#12288;{{
                  Dicts.DEVICE_CONN_MODE[props.row.communicationMode]
                }}</span
              >
            </el-form-item>
            <el-form-item label="设备板地址：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;{{ props.row.boardAddr }}</span
              >
            </el-form-item>
            <el-form-item label="设备IP地址：" class="tableExpanditem">
              <span class="tableExpandspan">{{ props.row.ipAddr }}</span>
            </el-form-item>
            <!-- <el-form-item label="升级状态" class="tableExpanditem">
              <span class="tableExpandspan">{{ props.row.upgradeStatus }}</span>
            </el-form-item> -->
            <el-form-item label="内存使用率：" class="tableExpanditem">
              <span class="tableExpandspan">{{ props.row.usedMem }}</span>
            </el-form-item>
            <el-form-item label="cpu使用率：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;&#32; {{ props.row.usedCpu }}</span
              >
            </el-form-item>
            <el-form-item label="通信号码：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;&#12288;{{ props.row.termiPhoneNum }}</span
              >
            </el-form-item>
            <el-form-item label="状态：" class="tableExpanditem">
              <span class="tableExpandspan">
                &#12288;&#12288;&#12288;{{
                  Dicts.DEVICE_CONNECT_STATUS[props.row.maintenanceStatus]
                }}</span
              >
            </el-form-item>
            <el-form-item label="创建时间：" class="tableExpanditem">
              <span class="tableExpandspan"
                >&#12288;{{ props.row.createTime }}</span
              >
            </el-form-item>
            <el-form-item label="最后上线时间：" class="tableExpanditem">
              <span class="tableExpandspan">{{
                props.row.lastOnlineTime
              }}</span>
            </el-form-item>
            <el-form-item label="最后离线时间：" class="tableExpanditem">
              <span class="tableExpandspan">{{
                props.row.lastOfflineTime
              }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column
        prop="name"
        label="设备名称"
        width="160"
        v-if="colData[0].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="snCode" label="SN编号" width="150" align="center">
      </el-table-column>

      <el-table-column
        prop="deviceCode"
        label="设备编号"
        width="110"
        v-if="colData[1].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="bussinessName"
        label="所属企业"
        width="100"
        v-if="colData[2].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="projectName"
        label="所属项目"
        width="120"
        v-if="colData[3].istrue"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.projectName ? scope.row.projectName : scope.row.projectId
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="deviceType"
        label="设备类型"
        width="100"
        v-if="colData[4].istrue"
        align="center"
      >
        <template slot-scope="scope">
          <span
            class="device-type"
            :class="{
              控制设备: scope.row.deviceType === '1',
              传输设备: scope.row.deviceType === '2'
            }"
          ></span>
          {{ Dicts.DEVICE_TYPE[scope.row.deviceType] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="local_hw_ver"
        label="硬件版本"
        width="100"
        v-if="colData[5].istrue"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.DEVICE_HARDWARE_VER[scope.row.localHwVer] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="localSwVer"
        label="软件版本"
        width="100"
        v-if="colData[6].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="communicationMode"
        label="连接方式"
        width="120"
        v-if="colData[7].istrue"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.DEVICE_CONN_MODE[scope.row.communicationMode] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="boardAddr"
        label="设备板地址"
        width="150"
        v-if="colData[8].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="ipAddr"
        label="设备IP地址"
        width="130"
        v-if="colData[9].istrue"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="usedMem"
        label="内存使用率"
        width="120"
        v-if="colData[10].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="usedCpu"
        label="cpu使用率"
        width="100"
        v-if="colData[11].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="termiPhoneNum"
        label="通信号码"
        width="150"
        v-if="colData[12].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="maintenanceStatus"
        label="状态"
        v-if="colData[13].istrue"
        align="center"
      >
        <template slot-scope="scope">
          <span
            class="device-status"
            :class="{
              online: scope.row.maintenanceStatus === '1',
              offline: scope.row.connectStatus === '2',
              sleep: scope.row.connectStatus === '5'
            }"
          ></span>
          {{ Dicts.DEVICE_CONNECT_STATUS[scope.row.maintenanceStatus] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="190"
        v-if="colData[14].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="lastOnlineTime"
        label="最后上线时间"
        width="155"
        v-if="colData[15].istrue"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="lastOfflineTime"
        label="最后离线时间"
        width="155"
        v-if="colData[16].istrue"
        align="center"
      >
      </el-table-column>

      <el-table-column
        prop="updateStatus"
        label="升级状态"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="
              scope.row.updateStatus === undefined ||
                scope.row.updateStatus === null
            "
            size="small"
            type="info"
          >
            未更新</el-tag
          >
          <el-tag v-if="scope.row.updateStatus === 0" size="small">
            更新中</el-tag
          >
          <el-tag
            v-if="scope.row.updateStatus === 1"
            size="small"
            type="success"
          >
            更新成功</el-tag
          >
          <el-tag
            v-if="scope.row.updateStatus === 2"
            size="small"
            type="danger"
          >
            更新失败</el-tag
          >
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="操作"
        v-if="colData[17].istrue"
        class-name="small-padding"
        fixed="right"
        width="430"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="'device:sync'"
            type="success"
            size="mini"
            @click="handleQueryById(scope.row.rowId)"
            title="同步"
            icon="el-icon-sort"
            circle
          ></el-button>
          <el-button
            v-permission="'device:edit'"
            size="mini"
            type="primary"
            @click="editDeviceById(scope.row)"
            title="编辑"
            icon="el-icon-edit"
            circle
          ></el-button>
          <el-button
            v-permission="'device:delete'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.rowId)"
            title="删除"
            icon="el-icon-delete"
            circle
          ></el-button>
          <el-button
            v-permission="'device:closeDevice'"
            size="mini"
            type="info"
            v-if="
              scope.row.maintenanceStatus === '2' ||
                scope.row.maintenanceStatus === '3' ||
                scope.row.maintenanceStatus === '4' ||
                scope.row.maintenanceStatus === '5' ||
                scope.row.maintenanceStatus === '6' ||
                scope.row.maintenanceStatus === '0'
            "
            @click="handleCloseDevice(scope.row)"
            title="上线"
            icon="el-icon-video-play"
            circle
          ></el-button>
          <el-button
            v-permission="'device:closeDevice'"
            size="mini"
            type="info"
            v-if="scope.row.maintenanceStatus === '1'"
            @click="handleCloseDevice(scope.row)"
            title="休眠"
            icon="el-icon-video-pause"
            circle
          ></el-button>
          <el-button
            v-permission="'device:vpnDevice'"
            size="mini"
            type="warning"
            v-if="
              scope.row.ipAddr === 'NULL' ||
                scope.row.ipAddr === undefined ||
                scope.row.ipAddr === '0.0.0.0' ||
                scope.row.ipAddr === ''
            "
            @click="handleVpnDevice(scope.row)"
            title="vpn连接"
            icon="el-icon-connection"
            circle
          ></el-button>
          <el-button
            v-permission="'device:vpnDevice'"
            size="mini"
            type="warning"
            v-if="
              scope.row.ipAddr != undefined &&
                scope.row.ipAddr != 'NULL' &&
                scope.row.ipAddr != '0.0.0.0' &&
                scope.row.ipAddr != ''
            "
            @click="handleVpnDevice(scope.row)"
            title="vpn断开"
            icon="el-icon-connection"
            circle
          ></el-button>
          <!-- <el-button
            v-permission="'device:update'"
            size="mini"
            type="primary"
            @click="handleSyncParam(scope.row.rowId)"
            title="升级"
            icon="el-icon-download"
            circle
          ></el-button> -->
          <el-button
            v-permission="'device:restart'"
            size="mini"
            type="success"
            @click="handleRestart(scope.row)"
            title="重启"
            icon="el-icon-refresh"
            circle
          ></el-button>
          <el-button
            v-permission="'device:monitor'"
            size="mini"
            type="warning"
            @click="handleOpenMonitor(scope.row.rowId)"
            title="监控"
            icon="el-icon-view"
            circle
          ></el-button>
          <el-button
            v-permission="'device:update'"
            size="mini"
            type="primary"
            @click="showPackageModal(scope.row.rowId, scope.row)"
            title="OTA升级"
            icon="el-icon-upload"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="'数据同步'"
      :visible.sync="dialogQueryDetailFormVisible"
      width="50%"
    >
      <el-form
        :model="detailForm"
        label-width="160px"
        :rules="detailFormRules"
        ref="detailForm"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="设备动态token:" prop="deviceAuthCode">
              <el-input
                :readonly="true"
                v-model="detailForm.deviceAuthCode"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="服务器动态token:" prop="authCode">
              <el-input
                :readonly="true"
                v-model="detailForm.authCode"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="设备内存总量:" prop="totalMem">
              <el-input
                :readonly="true"
                v-model="detailForm.totalMem"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备内存使用率:" prop="usedMem">
              <el-input
                :readonly="true"
                v-model="detailForm.usedMem"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="设备cpu总量:" prop="totalCpu">
              <el-input
                :readonly="true"
                v-model="detailForm.totalCpu"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备cpu使用率:" prop="usedCpu">
              <el-input
                :readonly="true"
                v-model="detailForm.usedCpu"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="设备IP地址:" prop="ipAddr">
              <el-input
                :readonly="true"
                v-model="detailForm.ipAddr"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1" style="margin-left: 170px;">
            <el-button
              size="mini"
              type="primary"
              title="IP上报"
              @click="handleIpSync()"
              icon="el-icon-top"
              circle
            ></el-button>
          </el-col>
          <el-col :span="1">
            <el-button
              size="mini"
              type="success"
              title="密钥同步"
              @click="handleSoftwareSync()"
              icon="el-icon-refresh-right"
              circle
            ></el-button>
          </el-col>
          <el-col :span="1">
            <el-button
              size="mini"
              type="info"
              title="性能数据同步"
              @click="handleCPUMEMSync()"
              icon="el-icon-refresh-left"
              circle
            ></el-button>
          </el-col>
          <el-col :span="1">
            <el-button
              size="mini"
              type="warning"
              title="重新对时"
              @click="handleUpdateTime()"
              icon="el-icon-pie-chart"
              circle
            ></el-button>
          </el-col>
          <el-col :span="1">
            <el-button
              size="mini"
              type="success"
              title="url同步"
              @click="handleUpdateUrl()"
              icon="el-icon-sort"
              circle
            ></el-button>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQueryDetailFormVisible = false"
          >关 闭</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="升级文件选择"
      :visible.sync="dialogModuleVisible"
      :before-close="handleDialogClose"
      width="40%"
    >
      <el-form :model="modules" label-width="200px" ref="module">
        <el-row>
          <el-col :span="24">
            <el-table
              :data="updateFilelist"
              style="width: 100%;margin: 40px,30px,40px,30px;"
            >
              <el-table-column prop="updateTemplate" label="模板名" width="180">
              </el-table-column>
              <el-table-column prop="updateFileName" label="文件名" width="180">
              </el-table-column>
              <el-table-column prop="updateFileID" label="文件ID" width="180">
              </el-table-column>
              <el-table-column
                align="center"
                label="操作"
                class-name="small-padding"
                width="180"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="DeleteUpdateFilelist(scope.row.updateFileID)"
                    title="删除"
                    icon="el-icon-delete"
                    circle
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-cascader
              :options="modules.modules"
              placeholder="试试搜索：模板名/文件名"
              ref="tree"
              size="medium "
              :props="{ value: 'id', label: 'label', children: 'children' }"
              filterable
              clearable
              style="width:650px;margin-left: 20px;margin-top: 30px;"
            >
            </el-cascader>

            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              @click="addupdateFilelist"
              type="success"
              circle
              title="添加"
              size="mini"
              icon="el-icon-plus"
            ></el-button>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeUpdateDialog">取 消</el-button>
        <el-button type="primary" @click="grantModulePower">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="OTA升级"
      :visible.sync="packageModalVisible"
      :before-close="handleClosePackageModal"
      width="20%"
    >
      <el-form :model="packageForm" :rules="packageFormRules" ref="packageForm">
        <el-row>
          <el-form-item label="服务器" prop="serviceId">
            <el-col :span="24">
              <el-select
                v-model="packageForm.serviceId"
                filterable
                placeholder="请选择服务器"
                style="width: 100%"
              >
                <el-option
                  v-for="item in serverList"
                  :key="item.rowId"
                  :label="`${item.name}`"
                  :value="item.rowId"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="更新包" prop="updatePackId">
            <el-col :span="24">
              <el-select
                v-model="packageForm.updatePackId"
                filterable
                placeholder="请选择更新包"
                style="width: 100%"
              >
                <el-option
                  v-for="item in packageList"
                  :key="item.rowId"
                  :label="`${item.name}(${item.versionNumber})`"
                  :value="item.rowId"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClosePackageModal">取 消</el-button>
        <el-button :loading="packageLoading" type="primary" @click="submitOta"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="新增设备"
      :visible.sync="dialogAddFormVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        label-width="160px"
        :rules="addFormRules"
        ref="addForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属项目:" prop="projectId">
              <el-select
                v-model="addForm.projectId"
                placeholder="请选择所属项目"
                style="width: 100%;"
                filterable
              >
                <el-option
                  v-for="(item, index) in projects"
                  :key="index"
                  :value="item.rowId"
                  :label="item.name"
                ></el-option>
              </el-select>
              <!-- <el-input
                v-model="addForm.projectId"
                placeholder="请输入所属项目"
                auto-complete="off"
              >
              </el-input> -->
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备名称:" prop="name">
              <el-input v-model="addForm.name" auto-complete="off"> </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="SN编号:" prop="snCode">
              <el-input v-model="addForm.snCode" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备类型:">
              <el-select
                v-model="addForm.deviceType"
                placeholder="可选"
                style="width: 100%;"
              >
                <el-option
                  v-for="(val, key) in Dicts.DEVICE_TYPE"
                  :key="key"
                  :label="val"
                  :value="key"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="板地址:" prop="boardAddr">
              <el-input
                v-model="addForm.boardAddr"
                auto-complete="off"
                maxlength="17"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="定时上传数据周期:" prop="alarmTaskTime">
              <el-input
                v-model="addForm.alarmTaskTime"
                auto-complete="off"
                maxlength="2"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="终端通讯号码:" prop="termiPhoneNum">
              <el-select
                v-model="addForm.termiPhoneNum"
                placeholder="请选择需绑定的通信卡"
                style="width: 100%;"
                filterable
              >
                <el-option
                  v-for="(item, index) in sims"
                  :key="index"
                  :value="item.phone"
                  :label="item.phone"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="软件版本:" prop="localHwVer">
              <el-select
                v-model="addForm.localHwVer"
                placeholder="必选"
                style="width: 100%;"
              >
                <el-option
                  v-for="(val, key) in Dicts.DEVICE_HARDWARE_VER"
                  :key="key"
                  :label="val"
                  :value="key"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="通讯方式:" prop="communicationMode">
              <el-select
                v-model="addForm.communicationMode"
                placeholder="必选"
                style="width: 100%;"
              >
                <el-option
                  v-for="(val, key) in Dicts.DEVICE_CONN_MODE"
                  :key="key"
                  :label="val"
                  :value="key"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设备编辑" :visible.sync="dialogFormVisible" width="50%">
      <el-form
        :model="detailForm"
        label-width="160px"
        :rules="detailFormRules"
        ref="detailForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属项目:" prop="projectId">
              <el-select
                v-model="detailForm.projectId"
                placeholder="请选择所属项目"
                style="width: 100%;"
                filterable
              >
                <el-option
                  v-for="(item, index) in projects"
                  :key="index"
                  :value="item.rowId"
                  :label="item.name"
                ></el-option>
              </el-select>
              <!-- <el-input
                v-model="addForm.projectId"
                placeholder="请输入所属项目"
                auto-complete="off"
              >
              </el-input> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称:" prop="name">
              <el-input v-model="detailForm.name" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="sn编号:" prop="snCode">
              <el-input v-model="detailForm.snCode" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>

          <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型:"
                          prop="deviceType">
              <el-select v-model="detailForm.deviceType"
                         placeholder="必选"
                         style="width: 100%;">
                <el-option v-for="(val, key) in Dicts.DEVICE_TYPE"
                           :key="key"
                           :label="val"
                           :value="key"
                           :disabled="false">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号:"
                          prop="deviceCode">
              <el-input v-model="detailForm.deviceCode"
                        auto-complete="off"
                        :disabled="true"
                        maxlength="2"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->

          <el-col :span="12">
            <el-form-item label="定时上传数据周期:" prop="alarmTaskTime">
              <el-input
                v-model="detailForm.alarmTaskTime"
                auto-complete="off"
                maxlength="2"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备鉴权码:" prop="authCode">
              <el-input
                :readonly="true"
                v-model="detailForm.authCode"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="终端通讯号码:" prop="termiPhoneNum">
              <el-input v-model="detailForm.termiPhoneNum" auto-complete="off" maxlength="14"></el-input>
              <el-select
                v-model="detailForm.termiPhoneNum"
                placeholder="请选择需绑定的通信卡"
                style="width: 100%;"
                filterable
              >
                <el-option
                  v-for="(item, index) in sims"
                  :key="index"
                  :value="item.phone"
                  :label="item.phone"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="通讯方式:" prop="communicationMode">
              <el-select
                v-model="detailForm.communicationMode"
                placeholder="必选"
                style="width: 100%;"
              >
                <el-option
                  v-for="(val, key) in Dicts.DEVICE_CONN_MODE"
                  :key="key"
                  :label="val"
                  :value="key"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveDetailForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="CPU/内存监视"
      :visible.sync="dialogCurveVisible"
      :append-to-body="true"
      :before-close="monitorDialogClose"
      width="50%"
    >
      <el-form ref="sizeForm" :model="sizeForm" label-width="80px" size="mini">
        <el-form-item>
          <el-col :span="12" style="padding-left:-10px;">
            <el-date-picker
              type="daterange"
              start-placeholder="开始日期"
              range-separator="至"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              v-model="sizeForm.pickerDate"
              @change="dateChangebirthday1"
              :picker-options="pickerOptions0"
              style="width: 420px;height:30px;align:center;font-size:20px;"
            ></el-date-picker>
          </el-col>
          <!-- </el-form-item>
        <el-form-item size="large"> -->
          <el-col :span="12" style="padding-left:15px;">
            <button class="button_name" @click="onSubmite">查询</button>
          </el-col>
        </el-form-item>
      </el-form>
      <div
        id="myChart"
        style="width:850px ;height:400px;left:25px;padding-top:30px;"
      ></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOtaLogs } from '@/api/ota'
import mqtt from 'mqtt' // import mqtt
// 监控图表
import echarts from 'echarts'
require('echarts/theme/macarons')

import {
  checkDeviceCodeExist,
  // checkBoardAddrExist,
  queryDeviceList,
  deleteDevice,
  queryDeviceDetail,
  saveDeviceDetail,
  addDevice,
  closeDevice,
  vpnDevice,
  syncParam,
  stateSync,
  ipSync,
  updateTime,
  userInfoSync,
  deviceRestart,
  getValidSimsList,
  findFileTree,
  updateFile,
  DeviceHistory,
  updateUrl
} from '@/api/device'

import { getAllPackegeList } from '@/api/ota'
import { getAllServerList } from '@/api/server'
import { startOTA } from '../../api/ota'

let mqttClient // mqtt client
// const username = 'Keisdom@190220' // mqtt username
// const password = 'mp@ssw0rd!Qaz2wSX' // mqtt password
// const url = 'ws://47.107.123.34:8083/mqtt' // mqtt path
const url = 'wss://m2150eb6.ala.cn-hangzhou.emqxsl.cn:8084/mqtt'
const username = 'admin' // mqtt username
const password = 'yiyao123' // mqtt password
const topics = { openDoorRecord: 0, monitBack: 2, demo: 0, '174452481/ip': 0 } // mqtt sub topics
const localUserId = Math.random() * 1000 // anychat local id
let remoteUserId // anychat remote userid
let roomId = 159 // anychat
const appkey = '45564eae-4767-4c43-9ee3-0a989d174c06' // anychat login appkey
const nickname = 'koss' // anychat nickname
export default {
  name: 'DeviceList',
  inject: ['reload'],
  data() {
    var checkDeviceCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('设备号不能为空'))
      }
      if (!/^[0-9]{10}$/.test(value)) {
        callback(new Error('请输入10位数字'))
      }
      checkDeviceCodeExist(value).then(({ data: { code, data, msg } }) => {
        if (code === 0 && data != null && data.deviceCode === value) {
          callback(new Error('已存在的设备号'))
        } else {
          callback()
        }
      })
    }
    var checkLocalHwVer = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('硬件类型不能为空'))
      } else {
        callback()
      }
    }
    var checkHandUpTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('呼叫挂断时间不能为空'))
      }
      if (!/^[0-9]{2}$/.test(value)) {
        callback(new Error('请输入2位数字'))
      } else {
        callback()
      }
    }
    var checkCallWaitTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('呼叫等待时间参数不能为空'))
      }
      if (!/^[0-9]{2}$/.test(value)) {
        callback(new Error('请输入2位数字'))
      } else {
        callback()
      }
    }
    var checkAlarmTaskTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('定时更新参数不能为空'))
      }
      if (!/^[0-9]{1,2}$/.test(value)) {
        callback(new Error('请输入2位数字'))
      } else {
        callback()
      }
    }
    var checkprojectId = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('所属企业不能为空'))
      } else {
        callback()
      }
    }

    return {
      // userMsg: { aa: 'device:monitor11' },
      serverList: [],
      packageList: [],
      packageForm: {
        deviceId: null
      },
      packageLoading: false,
      packageModalVisible: false,
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      dialogQueryDetailFormVisible: false,
      dialogCurveVisible: false,
      dialogModuleVisible: false,
      loading: false,
      options: [
        {
          value: 5000,
          label: '5秒'
        },
        {
          value: 60000,
          label: '1分钟'
        },
        {
          value: 300000,
          label: '5分钟'
        },
        {
          value: 1800000,
          label: '30分钟'
        },
        {
          value: 3600000,
          label: '1小时'
        }
      ],
      refreshTime: 60000,
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        importance: undefined,
        title: undefined
      },
      packageFormRules: {
        updatePackId: [
          { required: true, message: '请选择更新包', trigger: 'change' }
        ],
        serviceId: [
          { required: true, message: '请选择服务器', trigger: 'change' }
        ]
      },
      detailFormRules: {
        name: [
          {
            required: true,
            message: '请输入设备名称',
            trigger: 'blur'
          }
        ],
        snCode: [
          {
            required: true,
            message: '请输入设备序列号',
            trigger: 'blur'
          }
        ],
        termiAutoHandupTime: [{ validator: checkHandUpTime, trigger: 'blur' }],
        callWaitTime: [{ validator: checkCallWaitTime, trigger: 'blur' }],
        alarmTaskTime: [{ validator: checkAlarmTaskTime, trigger: 'blur' }]
      },
      addFormRules: {
        name: [
          {
            required: true,
            message: '请输入设备名称',
            trigger: 'blur'
          }
        ],
        snCode: [
          {
            required: true,
            message: '请输入设备序列号',
            trigger: 'blur'
          }
        ],
        deviceCode: [{ validator: checkDeviceCode, trigger: 'blur' }],
        localHwVer: [{ validator: checkLocalHwVer, trigger: 'blur' }],
        termiAutoHandupTime: [{ validator: checkHandUpTime, trigger: 'blur' }],
        callWaitTime: [{ validator: checkCallWaitTime, trigger: 'blur' }],
        alarmTaskTime: [{ validator: checkAlarmTaskTime, trigger: 'blur' }],

        projectId: [{ validator: checkprojectId, trigger: 'blur' }]
        // ,
        // projectId: [
        //   { required: true, message: "请选择所属项目", trigger: "blur" }
        // ]
      },
      detailForm: {
        rowId: 0,
        deviceCode: '',
        boardAddr: '',
        ethernetMac: '',
        videoCallFlag: '',
        callWaitTime: 0,
        termiAutoHandupTime: '',
        resolutionRatio: '',
        pictureQuality: '',
        lockOpenFlag: '',
        alarmTaskTime: '',
        restartTime: '',
        localHwVer: '',
        termiPhoneNum: '',
        volume: 0,
        callVolume: '',
        authCode: '',
        openDoorPwd: '',
        morningSoundStart: '',
        morningSoundEnd: '',
        afternoonSoundStart: '',
        afternoonSoundEnd: '',
        localSwVer: '',
        localUserVer: '',
        localWhiteVer: '',
        serverSoftwareVer: '',
        serverUserinfoVer: '',
        serverWhitecardVer: ''
      },
      addForm: {
        deviceCode: '',
        boardAddr: '',
        localHwVer: '',
        alarmTaskTime: '',
        ethernetMac: '',
        videoCallFlag: '',
        lockOpenFlag: '',
        resolutionRatio: '',
        volume: '',
        callVolume: ''
      },
      paramTempForm: {},
      connectStatus: Dicts.DEVICE_CONNECT_STATUS,
      records: [],
      sims: [],
      projects: [],
      templateRecords: [],
      modules: { modules: [] }, // 模块树节点集合
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      updateFilelist: [],
      updateFilebox: {
        updateTemplate: '',
        updateFileName: '',
        updateFileID: ''
      },
      updateFileNum: 0,
      rolePower: {
        deviceId: undefined,
        keys: [] // 文件选中的节点集合
      },
      deviceId: undefined, // 权限分配时保存的角色ID
      dataCurve: {
        echatX: [],
        CPU: [],
        Memory: []
      },
      sizeForm: {
        pickerDate: [],
        params: {}
      },
      rowIdForm: {},
      fileNodes: [],
      pickerOptions0: {
        disabledDate(time) {
          // 配合:picker-options  > 表示禁选当前天之后。< 表示禁选当前天之前- 8.64e6
          return time.getTime() > Date.now()
        }
      },
      colData: [
        { title: '设备名称', istrue: true },
        { title: '设备编号', istrue: true },
        { title: '所属企业', istrue: false },
        { title: '所属项目', istrue: false },
        { title: '设备类型', istrue: false },
        { title: '硬件版本', istrue: false },
        { title: '软件版本', istrue: false },
        { title: '连接方式', istrue: false },
        { title: '设备板地址', istrue: false },
        { title: '设备IP地址', istrue: true },
        { title: '内存使用率', istrue: true },
        { title: 'cpu使用率', istrue: true },
        { title: '通信号码', istrue: false },
        { title: '状态', istrue: true },
        { title: '创建时间', istrue: false },
        { title: '最后上线时间', istrue: true },
        { title: '最后离线时间', istrue: true },
        // { title: '升级状态', istrue: false },
        { title: '操作', istrue: true }
      ],
      colOptions: [
        '设备名称',
        // '所属项目',
        // '连接方式',
        // '设备类型',
        '设备编号',
        // '设备板地址',
        '设备IP地址',
        '内存使用率',
        'cpu使用率',
        '状态',
        '最后上线时间',
        '最后离线时间',
        // '升级状态',
        '操作'
      ], // 默认选中的
      colSelect: [
        '设备名称',
        '设备编号',
        '所属企业',
        '所属项目',
        '设备类型',
        '硬件版本',
        '软件版本',
        '连接方式',
        '设备板地址',
        '设备IP地址',
        '内存使用率',
        'cpu使用率',
        '通信号码',
        '状态',
        '创建时间',
        '最后上线时间',
        '最后离线时间',
        // '升级状态',
        '操作'
      ] // 所有选项
    }
  },
  // 取
  // beforeMount() {
  //      this.userMsg = JSON.parse(sessionStorage.getItem('userMsg'));
  // },
  // 存
  // beforeUpdate() {
  //   this.userMsg={ aa: 'device:monitor11' }
  //   sessionStorage.setItem("userMsg",JSON.stringify(this.userMsg));
  // },
  // beforeCreate () {

  // },
  // 元素挂在完成后，触发定时刷新任务
  mounted() {
    if (this.timer) {
      clearInterval(this.timer)
    } else {
      this.timer = setInterval(() => {
        this.doQuery()
      }, this.refreshTime)
    }
  },
  // 页面销毁时清除定时器
  destroyed() {
    clearInterval(this.timer)
  },
  created() {
    this.doQuery()
    // console.log('mqtt connecting')
    mqttClient = mqtt.connect(url, {
      username,
      password
    })
    // 订阅主题
    mqttClient.subscribe(topics)

    // connect event
    mqttClient.on('connect', () => {
      // console.log('mqtt connected')
    })
    // reconnect event
    mqttClient.on('reconnect', () => {
      // console.log('mqtt reconnected')
    })
    // close event
    mqttClient.on('close', () => {
      // console.log('mqtt closed')
    })
    // end event
    mqttClient.on('end', () => {
      // console.log('mqtt end')
    })
    // offline event
    mqttClient.on('offline', () => {
      // console.log('mqtt offline')
    })
    // error event
    mqttClient.on('error', error => {
      // console.log('mqtt error:' + error)
    })
    // send pack event
    mqttClient.on('packetsend', packet => {
      // console.log('mqtt packetsend:' + packet)
    })
    // receve pack event(include heartpack and message)
    mqttClient.on('packetreceive', packet => {
      // console.log('mqtt packetreceive:' + packet)
    })
    // receve subscribe topic message event
    mqttClient.on('message', (topic, message) => {
      // console.log('message arrived, topic:' + topic + '|message:' + message)
      var obj = JSON.parse(message.toString())
      if (message == '123') {
        // mqttClient.publish(
        //   topic,
        //   {
        //     message: '测试发送消息'
        //   },
        //   { qos: 1, retain: true },
        //   error => {
        //     if (error) {
        //       console.log(error)
        //     } else {
        //       console.log('已发送')
        //     }
        //   }
        // )
      }
      // bussiness here
      if (topic === 'monitBack') {
        // monitor response topic
        // console.log('monit start')
        // const flag = obj.flag
        roomId = obj.roomId
        const deviceId = obj.deviceId
        remoteUserId = deviceId.substr(5, 9)
        // console.log('flag:' + flag + ' roomId:' + roomId + ' deviceId:' + deviceId)
        const videoId = 'remoteVideo'
        this.$alert(
          `<div><div id=${videoId} style="width: 400px;height:300px;"></div></div>`,
          '视频监控',
          {
            dangerouslyUseHTMLString: true,
            callback: () => {
              this.anychat.leaveRoom(roomId, remoteUserId) // release local resource
              const data = {
                deviceId: deviceId,
                flag: '1', // close monitor flag
                roomId: roomId
              }
              mqttClient.publish('monit/' + deviceId, JSON.parse(data)) // notify device release resource
              // console.log('resource release')
            }
          }
        )
        this.anychat
          .login({
            // anychat login function(include init sdk, login method)
            nickname: nickname,
            userId: localUserId,
            appKey: appkey
          })
          .then(() => {
            this.anychat.enterRoom(roomId).then(() => {
              // anychat enterRoom function
              setTimeout(() => {
                this.anychat.controlCameraAndSpeak(remoteUserId) // open remote device camera and speaker
                this.anychat.setVideoPos(remoteUserId, videoId) // draw video interface
              }, 2000)
            })
          })
      } else if (topic === 'openDoorRecord') {
        // openDoorRecord Bussiness
        // const community = obj.communityName
        // const building = obj.buildingName
        // const unit = obj.unitName
        // const room = obj.houseNumber
        // const username = obj.openName
        // const url = obj.openPhoto
        // const communityCode = obj.communityCode
        // this.opendoorimg = url
        // console.log('community:' + community + ' building:' + building + ' unit:' + unit + ' room:' + room + ' username:' + username + ' url:' + url + ' communitycode:' + communityCode)
        // console.log('openDoorRecord Bussiness here')
      }
    })
  },
  watch: {
    // 监听dataCurve对象的变化
    dataCurve: {
      deep: true,
      handler: function(newVal) {
        // console.log('渲染图表数据', newVal)
        // 重新渲染折线图
        this.$nextTick(() => this.initchart())
      }
    },
    refreshTime: {
      deep: true,
      handler: function(newVal) {
        clearInterval(this.timer)
        this.timer = setInterval(() => {
          this.doQuery()
        }, this.refreshTime)
      }
    },
    // 监听选择列
    colOptions(valArr) {
      var arr = this.colSelect.filter(i => valArr.indexOf(i) < 0) // 未选中
      this.colData.filter(i => {
        if (arr.indexOf(i.title) !== -1) {
          i.istrue = false
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout()
          })
        } else {
          i.istrue = true
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout()
          })
        }
      })
    }
  },

  methods: {
    fetchServerList() {
      getAllServerList().then(({ data: { data } }) => {
        this.serverList = data
      })
    },
    fetchPackageList() {
      getAllPackegeList().then(({ data: { data } }) => {
        this.packageList = data
      })
    },
    submitOta() {
      this.$refs.packageForm.validate(valid => {
        if (valid) {
          const params = {
            serviceId: this.packageForm.serviceId,
            updatePackId: this.packageForm.updatePackId,
            deviceId: this.packageForm.deviceId
          }
          this.packageLoading = true
          startOTA(params)
            .then(({ data: { data, msg, code } }) => {
              this.packageLoading = false
              if (code === 0) {
                this.doQuery()
                this.handleClosePackageModal()
              }
              this.$message({
                showClose: true,
                message: code === 0 ? '操作成功' : msg,
                type: code === 0 ? 'success' : 'error'
              })
            })
            .catch(error => {
              this.packageLoading = false
            })
        }
      })
    },
    handleClosePackageModal() {
      this.$refs.packageForm.resetFields()
      this.packageModalVisible = false
      this.packageForm = {}
    },
    showPackageModal(id, row) {
      this.fetchPackageList()
      this.fetchServerList()
      this.packageForm.deviceId = id
      this.packageForm.snCode = row.snCode
      this.packageModalVisible = true
    },
    handleSortChange({ column, prop, order }) {
      this.queryForm.ascs = ''
      this.queryForm.descs = ''
      if (order) {
        if (order === 'ascending') {
          this.queryForm.ascs = column.sortBy
        } else {
          this.queryForm.descs = column.sortBy
        }
      }
      this.queryForm.current = 0
      this.doQuery()
    },
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    doSearchQuery() {
      this.queryForm.current = 1
      this.doQuery()
    },

    // doQuery() {
    //   this.loading = true
    //   queryDeviceList(this.queryForm).then(({ data: { data } }) => {
    //     // this.queryForm.current = data.current
    //     // this.queryForm.pages = data.pages
    //     // this.queryForm.total = data.total
    //     // this.queryForm.size = data.size
    //     // this.records = data.records
    //     // this.loading = false
    //     getOtaLogs({ pages: 1, size: 10000 }).then(({ data: { content } }) => {
    //     })
    //   })
    // },

    async doQuery() {
      this.loading = true
      try {
        // 查询设备列表
        const { data: deviceResponse } = await queryDeviceList(this.queryForm)

        // 查询OTA日志
        const { data: logResponse } = await getOtaLogs({
          pages: 1,
          size: 10000
        })

        // 处理日志数据
        const logRecords = logResponse.data.records
        const records = deviceResponse.data.records

        records.forEach((device, index) => {
          const firstLog = logRecords.find(
            log => log.deviceName === device.name
          )
          if (firstLog) {
            records[index].updateStatus = firstLog.updateStatus
          }
        })

        this.queryForm.current = deviceResponse.data.current
        this.queryForm.pages = deviceResponse.data.pages
        this.queryForm.total = deviceResponse.data.total
        this.queryForm.size = deviceResponse.data.size
        this.records = records
      } catch (error) {
        console.error('请求失败', error)
      } finally {
        this.loading = false
      }
    },

    timeChange() {},
    // 监听升级弹窗右上关闭，清空内容
    handleDialogClose() {
      this.clearUpdatefile()
      this.clearCascaderValue()
    },
    // 升级弹窗取消按钮
    closeUpdateDialog() {
      this.clearCascaderValue()
      this.clearUpdatefile()
    },
    // 清空级联选择器
    clearCascaderValue() {
      const obj = {}
      obj.stopPropagation = () => {}
      try {
        this.$refs.tree.clearValue(obj)
      } catch (err) {
        this.$refs.tree.handleClear(obj)
      }
    },
    // 清空升级文件对象,并关闭升级弹窗
    clearUpdatefile() {
      this.dialogModuleVisible = false
      this.fileNodes = []
      this.rolePower = {}
      this.updateFilebox = {}
      this.updateFilelist = []
      this.updateFileNum = 0
    },
    // 添加升级文件
    addupdateFilelist() {
      this.updateFilebox = {}
      var num = this.updateFileNum++
      // console.log("计数器", aa)
      this.fileNodes = this.$refs.tree.getCheckedNodes()
      // console.log("节点", this.fileNodes)
      // 判断是否选中文件
      if (this.fileNodes.length !== 0) {
        this.updateFilebox.updateTemplate = this.fileNodes[0].pathLabels[0]
        this.updateFilebox.updateFileName = this.fileNodes[0].label
        this.updateFilebox.updateFileID = this.fileNodes[0].value
        if (num === 0) {
          this.updateFilelist.push(this.updateFilebox)
        } else {
          // 判断是否选中重复文件
          for (var i = 0; i < this.updateFilelist.length; i++) {
            if (
              this.updateFilelist[i].updateFileID ===
              this.updateFilebox.updateFileID
            ) {
              this.$message({
                showClose: true,
                message: '该文件已选择',
                type: 'warning'
              })
              return
            }
          }
          this.updateFilelist.push(this.updateFilebox)
        }
      } else {
        this.$message({
          showClose: true,
          message: '不能添加空文件',
          type: 'warning'
        })
      }
      // console.log(this.updateFilelist)
    },
    // 删除选中的升级文件
    DeleteUpdateFilelist(updateFileID) {
      // console.log(updateFileID)
      // 删除选中的行
      for (var i = 0; i < this.updateFilelist.length; i++) {
        if (this.updateFilelist[i].updateFileID === updateFileID) {
          this.updateFilelist.splice(i, 1)
        }
      }
      // console.log(this.updateFilelist)
    },
    // 确定提交升级文件
    grantModulePower() {
      this.rolePower.deviceId = this.deviceId
      this.updateFilelist.forEach((item, index) => {
        this.rolePower.keys[index] = item.updateFileID
      })
      if (this.rolePower.keys.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择升级文件',
          type: 'warning'
        })
        return false
      }
      // console.log("升级传给后台的参数", this.rolePower)
      updateFile(this.rolePower).then(({ data: { data, msg, code } }) => {
        if (code === 0) {
          this.doQuery()
          this.clearCascaderValue()
          this.clearUpdatefile()
        }
        this.$message({
          showClose: true,
          message: msg,
          type: code === 0 ? 'success' : 'error'
        })
      })
    },
    handleQueryById(rowId) {
      this.loading = true
      queryDeviceDetail(rowId).then(({ data: { code, data, msg } }) => {
        this.loading = false
        if (code === 0) {
          this.openQueryDetailDialog()
          this.detailForm = {
            rowId: data.rowId,
            deviceCode: data.deviceCode,
            deviceAuthCode: data.deviceAuthCode,
            authCode: data.authCode,
            usedCpu: data.usedCpu,
            totalCpu: data.totalCpu,
            usedMem: data.usedMem,
            totalMem: data.totalMem,
            ipAddr: data.ipAddr,
            devicelastUpdateTime: data.deviceLastUpdateTime
          }
          // console.log(this.detailForm)
        }
      })
    },
    handleDelete(rowId) {
      this.$confirm('此操作将永久删除该示例, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteDevice(rowId).then(({ data: { data, msg } }) => {
          this.loading = false
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    editDeviceById({ rowId }) {
      this.loading = true
      queryDeviceDetail(rowId).then(({ data: { code, data, msg } }) => {
        this.loading = false
        if (code === 0) {
          this.openEditDialog()
          this.detailForm = {
            rowId: data.rowId,
            name: data.name,
            projectId: data.projectId,
            deviceCode: data.deviceCode,
            boardAddr: data.boardAddr,
            ethernetMac: data.ethernetMac,
            localHwVer: data.localHwVer,
            termiPhoneNum: data.termiPhoneNum,
            authCode: data.authCode,
            snCode: data.snCode,
            communicationMode: data.communicationMode,
            deviceType: data.deviceType,
            alarmTaskTime: data.alarmTaskTime
          }
        }
      })
    },
    openEditDialog() {
      this.detailForm = {}
      this.dialogFormVisible = true
      getValidSimsList().then(({ data: { code, data, msg } }) => {
        this.loading = false
        if (code === 0) {
          this.sims = data.sims
          this.projects = data.projects
        }
      })
      this.$refs.detailForm && this.$refs.detailForm.resetFields()
    },
    openModuleDialog() {
      // this.modules.modules = []
      this.modules.modules = []
      this.dialogModuleVisible = true
      // this.$refs.modules && this.$refs.modules.resetFields()
    },
    openCreateDialog() {
      this.loading = true
      getValidSimsList().then(({ data: { code, data, msg } }) => {
        // console.log(data)
        this.loading = false
        if (code === 0) {
          this.sims = data.sims
          this.projects = data.projects
        }
      })

      this.addForm = {
        videoCallFlag: '0',
        lockOpenFlag: '0',
        resolutionRatio: '0',
        volume: 0.5,
        callVolume: 5,
        localHwVer: '4',
        alarmTaskTime: '30'
      }
      this.dialogAddFormVisible = true
      this.$refs.addForm && this.$refs.addForm.resetFields()
    },

    openQueryDetailDialog() {
      this.detailForm = {}
      this.dialogQueryDetailFormVisible = true
      this.$refs.detailForm && this.$refs.detailForm.resetFields()
    },
    saveDetailForm() {
      this.$refs.detailForm.validate(valid => {
        if (valid) {
          saveDeviceDetail(this.detailForm).then(
            ({ data: { data, msg, code } }) => {
              if (code === 0) {
                this.doQuery()
                this.dialogFormVisible = false
              }
              this.$message({
                showClose: true,
                message: msg,
                type: code === 0 ? 'success' : 'error'
              })
            }
          )
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    getTemplateDetail(rowId) {
      const data = this.templateRecords.find(item => item.rowId === rowId)
      // console.log(data)
      this.addForm = {
        videoCallFlag: data.videoCallFlag,
        callWaitTime: data.callWaitTime,
        termiAutoHandupTime: data.termiAutoHandupTime,
        resolutionRatio: data.resolutionRatio,
        lockOpenFlag: data.lockOpenFlag,
        alarmTaskTime: data.alarmTaskTime,
        localHwVer: data.localHwVer,
        termiPhoneNum: data.termiPhoneNum,
        volume: parseFloat(data.volume),
        callVolume: data.callVolume,
        authCode: data.authCode,
        bluetoothToken: data.bluetoothToken,
        morningSoundStart: data.morningSoundStart,
        morningSoundEnd: data.morningSoundEnd,
        afternoonSoundStart: data.afternoonSoundStart,
        afternoonSoundEnd: data.afternoonSoundEnd
      }
      // console.log(rowId)
    },
    saveAddForm() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          addDevice(this.addForm)
            .then(({ data: { data, msg, code } }) => {
              this.doQuery()
              this.dialogAddFormVisible = false
              this.$message({
                showClose: true,
                message: msg,
                type: 'success'
              })
            })
            .catch(_ => {
              this.loading = false
            })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    handleCloseDevice(form) {
      // this.loading = true
      closeDevice(form)
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
      setTimeout(this.doQuery, 3000)
    },
    handleVpnDevice(form) {
      this.loading = true
      vpnDevice(form)
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleSyncParam(rowId) {
      this.loading = false
      this.deviceId = rowId
      findFileTree(rowId).then(({ data: { data } }) => {
        // console.log(data.module)
        this.openModuleDialog()
        this.modules.modules = data.module
      })
    },
    handleUserInfoSync() {
      this.loading = true
      userInfoSync({ deviceCode: this.detailForm.deviceCode })
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleSoftwareSync() {
      this.loading = true
      syncParam({ deviceCode: this.detailForm.deviceCode })
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleIpSync() {
      this.loading = true
      ipSync({ deviceCode: this.detailForm.deviceCode })
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleUpdateTime() {
      this.loading = true
      updateTime({ deviceCode: this.detailForm.deviceCode })
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleUpdateUrl() {
      this.loading = true
      updateUrl({ deviceCode: this.detailForm.deviceCode })
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleCPUMEMSync() {
      this.loading = true
      stateSync({ deviceCode: this.detailForm.deviceCode })
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleRestart(form) {
      this.loading = true
      deviceRestart(form)
        .then(({ data: { code, data, msg } }) => {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
        .catch(_ => {
          this.loading = false
        })
    },
    handleOpenMonitor(rowId) {
      // 打开弹窗
      this.dialogCurveVisible = true
      // 拿到设备编号deviceCode
      this.rowIdForm.rowId = rowId
      // console.log(deviceCode)
      // 初始化折线
      this.$nextTick(() => this.initchart())
    },
    onSubmite() {
      // 请求数据
      DeviceHistory(this.sizeForm.params).then(({ data: { data } }) => {
        this.loading = false
        // 获取日期选择的间隔值,并且给X轴赋值
        // var bd = new Date(this.sizeForm.params.begin)
        // var be = new Date(this.sizeForm.params.end)
        // var bd_time = bd.getTime()
        // var be_time = be.getTime()
        // var time_diff = be_time - bd_time
        // var d_arr = []
        // for (var i = 0; i <= time_diff; i += 86400000) {
        //   var ds = new Date(bd_time + i)
        //   d_arr.push(ds.getFullYear() + '-' + (ds.getMonth() + 1) + '-' + ds.getDate())
        // }
        // 给折线图数据赋值
        //  console.log('请求到的数据', data)
        var d_arr = data.cpus
        var d_arr_init = []
        for (var k in d_arr) {
          var d = new Date(parseInt(k))
          var d_init =
            d.getFullYear() +
            '-' +
            (d.getMonth() + 1) +
            '-' +
            d.getDate() +
            ' ' +
            d.getHours() +
            ':' +
            d.getMinutes() +
            ':' +
            d.getSeconds()
          d_arr_init.push(d_init)
        }
        this.dataCurve.CPU = Object.values(data.cpus)
        this.dataCurve.Memory = Object.values(data.mems)
        this.dataCurve.echatX = d_arr_init
      })
    },
    // 关闭监视弹框右上角的事件
    monitorDialogClose() {
      this.dialogCurveVisible = false
      this.dataCurve = {
        echatX: [],
        CPU: [],
        Memory: []
      }
      this.sizeForm = {
        pickerDate: [],
        params: {}
      }
    },
    // 关闭弹框的事件
    closeDialog() {
      this.dialogCurveVisible = false
      this.dataCurve = {
        echatX: [],
        CPU: [],
        Memory: []
      }
      this.sizeForm = {
        pickerDate: [],
        params: {}
      }
      // console.log(this.dataCurve)
    },
    dateChangebirthday1(val) {
      // 获取日期选择器选择的值
      var data2 = val
      // console.log('选择的日期', data2)
      // 给传给后台的form表单参数赋值
      // 当获取到后台的数据后，如果不为空或空字符串，就赋值。
      if (data2 !== null) {
        if (data2.property !== null) {
          this.sizeForm.params.begin = data2[0]
          this.sizeForm.params.end = data2[1]
          this.sizeForm.params.deviceId = this.rowIdForm.rowId
          // console.log('传给后台的参数', this.sizeForm.params)
        }
      }
    },
    // 初始化折线
    initchart() {
      const myChart = echarts.init(document.getElementById('myChart'))
      myChart.setOption(
        {
          title: {
            left: 'left',
            text: '概率',
            show: false
          },
          grid: {
            x: 65,
            y: 45,
            x2: 75,
            y2: 45
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['CPU', 'Memory']
          },
          toolbox: {
            show: true,
            right: 30, // 是否显示工具栏组件
            itemSize: 20, // 工具栏 icon 的大小
            showTitle: true, // 是否在鼠标 hover 的时候显示每个工具 icon 的标题
            feature: {
              mark: {
                // '辅助线开关'
                show: true
              },
              // dataView: {
              //   show: true,
              //   title: '数据视图',
              //   readOnly: true,
              //   lang: ['数据视图', '关闭'],
              //   optionToContent: function(opt) {
              //     var axisData = opt.xAxis[0].data
              //     var series = opt.series
              //     var tdHeads = '<td  style="padding:0 10px">名称</td>'
              //     series.forEach(function(item) {
              //       tdHeads += '<td style="padding: 3px 10px">' + item.name + '</td>'
              //     })
              //     var table = '<table border="1" style="margin-left:20px;border-collapse:collapse;font-size:18px;text-align:center"><tbody><tr>' + tdHeads + '</tr>'
              //     var tdBodys = ''
              //     for (var i = 0, l = axisData.length; i < l; i++) {
              //       for (var j = 0; j < series.length; j++) {
              //         if (typeof (series[j].data[i]) === 'object') {
              //           tdBodys += '<td>' + series[j].data[i].value + '</td>'
              //         } else {
              //           tdBodys += '<td>' + series[j].data[i] + '</td>'
              //         }
              //       }
              //       table += '<tr><td style="padding: 3px 10px">' + axisData[i] + '</td>' + tdBodys + '</tr>'
              //       tdBodys = ''
              //     }
              //     table += '</tbody></table>'
              //     return table
              //   }
              // },
              // magicType: { // 动态类型切换
              //   show: true,
              //   title: '切换', // 各个类型的标题文本，可以分别配置。
              //   type: ['bar', 'line'] // 启用的动态类型，包括'line'（切换为折线图）, 'bar'（切换为柱状图）, 'stack'（切换为堆叠模式）, 'tiled'（切换为平铺模式）
              // },
              restore: {
                // 配置项还原。
                show: true, // 是否显示该工具。
                title: '还原'
              },
              saveAsImage: {
                // 保存为图片。
                show: true, // 是否显示该工具。
                type: 'png', // 保存的图片格式。支持 'png' 和 'jpeg'。
                name: 'pic1', // 保存的文件名称，默认使用 title.text 作为名称
                backgroundColor: '#ffffff', // 保存的图片背景色，默认使用 backgroundColor，如果
                title: '保存为图片',
                pixelRatio: 1 // 保存图片的分辨率比例，默认跟容器相同大小，如果需要保存更高分辨率的，可以设置为大于 1 的值，例如 2
              },
              dataZoom: {
                // 数据区域缩放。目前只支持直角坐标系的缩放
                show: true, // 是否显示该工具。
                title: '缩放', // 缩放和还原的标题文本
                xAxisIndex: 0, // 指定哪些 xAxis 被控制。如果缺省则控制所有的x轴。如果设置为 false 则不控制任何x轴。如果设置成 3 则控制 axisIndex 为 3 的x轴。如果设置为 [0, 3] 则控制 axisIndex 为 0 和 3 的x轴
                yAxisIndex: false // 指定哪些 yAxis 被控制。如果缺省则控制所有的y轴。如果设置为 false 则不控制任何y轴。如果设置成 3 则控制 axisIndex 为 3 的y轴。如果设置为 [0, 3] 则控制 axisIndex 为 0 和 3 的y轴
              }
            }
          },
          xAxis: {
            type: 'category',
            splitLine: { show: false },
            name: '日期',
            data: this.dataCurve.echatX,
            axisPointer: {
              type: 'line'
            },
            axisLabel: {
              rotate: 8
            }
          },
          // 设置两个y轴，左边显示数量，右边显示概率
          yAxis: [
            {
              splitLine: { show: false },
              type: 'value',
              name: '百分比',
              show: true
            }
          ],
          // 每个设备分数量、概率2个指标，只要让他们的name一致，即可通过，legeng进行统一的切换
          series: [
            {
              name: 'CPU',
              type: 'line',
              symbol: 'circle', // 折线点设置为实心点
              symbolSize: 5, // 折线点的大小
              data: this.dataCurve.CPU,
              barWidth: 30,
              itemStyle: {
                normal: {
                  color: '#b6a2de',
                  lineStyle: {
                    color: '#b6a2de'
                  }
                }
              }
            },
            {
              name: 'Memory',
              type: 'line',
              symbol: 'circle', // 折线点设置为实心点
              symbolSize: 5, // 折线点的大小
              data: this.dataCurve.Memory,
              itemStyle: {
                normal: {
                  color: '#2ec7c9',
                  lineStyle: {
                    color: '#2ec7c9'
                  }
                }
              }
            }
          ]
        },
        true
      )
    }
  },
  components: {}
}
</script>

<style scoped lang="scss">
.button_name {
  width: 80px;
  height: 30px;
  background-color: #67c23a;
  font-size: 15px;
  border-radius: 4px;
  color: white;
  border: none;
  outline: none;
  text-align: center;
  text-decoration: none;
  display: inline-block;
}
.button_name {
  -webkit-transition-duration: 0.2s; /* Safari */
  transition-duration: 0.2s;
}
.button_name:hover {
  background-color: #85ce61; /* Green */
  color: white;
}
.tableExpand {
  font-size: 0;
  width: 1200px;
}
.tableExpanditem {
  margin-right: 0;
  margin-bottom: 0;
  width: 300px;
}
.tableExpandspan {
  color: #409eff;
}
.device-status {
  width: 8px;
  height: 8px;
  margin-right: 3px;
  border-radius: 50%;
  display: inline-block;
  background: #a7a7a7;
  &.online {
    background: green;
  }
  &.offline {
    background: red;
  }
  &.sleep {
    background: gray;
  }
}
</style>
